import requests
from pyquery import PyQuery as pq
# 获取网页内容同
def getPage():
    url = 'https://cart.jd.com/cart.action'

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'cookie': 'ipLoc-djd=1-72-4137-0; areaId=1; __jdv=122270672|direct|-|none|-|1544771827278; __jdu=15447718272781330857716; shshshfpa=e11dd0ea-93d2-f7e8-4f5c-15ecd326bcbb-1545011627; user-key=891c1bd3-0074-42d8-80df-9b4c0bc33ab9; mt_xid=V2_52007VwMWV1heVFoWSh9fA24DEFBcUVZcGUkebANgBBRQVFhSRhhIGFgZYgITU0ELUF8fVUoMAmcHR1AOUFpSGnkaXQVuHxJRQVhUSx5BElgHbAcaYl9oUmodShpYBGMEE1BtWFdcGA%3D%3D; __jda=122270672.15447718272781330857716.1544771827.1545011627.1545633707.3; __jdc=122270672; PCSYCityID=904; 3AB9D23F7A4B3C9B=ZFM2EEYYEUE2IZZVPPZJJ57AATHNN37IZNL2JMUHXVWNDGRGIXTUCWOYNV3TC44MUQZ5ZBTZUFVERWSDGFE6KX3CRI; _gcl_au=1.1.2007228161.1545633726; shshshfpb=rRkC1x%2Br8NbQYmCZkLV63Aw%3D%3D; cart-main=xx; cn=4; cd=0; shshshfp=7e585e754120a2e6751ff50d8b90ed03; shshshsID=fa5d8d6344f3a1291127fde54ba228ba_10_1545633804994; __jdb=122270672.16.15447718272781330857716|3.1545633707',
        'referer': 'https://cart.jd.com/addToCart.html?rcd=1&pid=4335045&pc=1&eb=1&rid=1545633799815&em=',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36',
    }

    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
    except requests.ConnectionError:
        return None

# 解析数据
def parsePage(content):
    html = pq(content)
    items = html('div.item-form')
    for item in items.items():
        yield {
            'img':item.find('div.goods-item div.p-img a img').attr('src'),
            'pname':item.find('div.goods-item div.item-msg div.p-name a').text(),
            'params':item.find('div[class="cell p-props p-props-new"] div.props-txt').text(),
            'perprice':item.find('div[class="cell p-price p-price-new "] p strong').text(),
            'num':item.find('div.p-quantity input').attr('value'),
            'sumprice':item.find('div.p-sum strong').text(),
        }
# 主函数
def main():
    html = getPage()
    if html:
        for item in parsePage(html):
            print(item)


if __name__ == '__main__':
    main()